<template>
  <div class="news-page">
    <div class="news-header">
      <h1 class="news-title">新闻资讯</h1>
      <p class="news-desc">时刻关注新闻资讯，我们会第一时间提供更多编程行业信息，不定期报道国内少儿编程赛事等资讯。</p>
    </div>
    
    <div class="news-container">
      <div class="news-actions">
        <button class="btn btn-refresh" @click="refreshNews" :disabled="loading">
          {{ loading ? '刷新中...' : '刷新' }}
        </button>
        <button class="btn btn-create" @click="createNews">新建新闻</button>
      </div>
      
      <div v-if="loading" class="loading-container">
        <div class="loading-spinner"></div>
        <p>加载中...</p>
      </div>
      
      <ul v-else class="news-list">
        <li class="news-item" v-for="(item, index) in newsList" :key="index">
          <div class="news-item-content">
            <div class="news-info">
              <span class="news-date">{{ item.date }}</span>
              <h3 class="news-item-title">{{ item.title }}</h3>
            </div>
            <div class="news-item-actions">
              <router-link :to="`/news/detail/${item.id}`" class="view-detail">查看详情</router-link>
              <button @click="deleteNews(item)" class="btn btn-delete-item">删除</button>
            </div>
          </div>
        </li>
      </ul>
      
      <div class="pagination">
        <span>（共 {{ total }} 条）</span>
        <a href="#" class="page-btn" @click.prevent="prevPage" :class="{ disabled: currentPage === 1 }">上一页</a>
        <span v-for="page in pages" :key="page" class="page-number" 
              :class="{ active: currentPage === page }"
              @click="goToPage(page)">{{ page }}</span>
        <a href="#" class="page-btn" @click.prevent="nextPage" :class="{ disabled: currentPage === totalPages }">下一页</a>
      </div>
    </div>
  </div>
</template>

<script>
import { newsApi } from '@/api'
import logger from '../utils/logger.js'

export default {
  name: 'NewsView',
  data() {
    return {
      currentPage: 1,
      pageSize: 10,
      total: 0,
      newsList: [],
      loading: false
    };
  },
  computed: {
    totalPages() {
      return Math.ceil(this.total / this.pageSize);
    },
    pages() {
      const pageArray = [];
      for (let i = 1; i <= this.totalPages; i++) {
        pageArray.push(i);
      }
      return pageArray;
    }
  },
  mounted() {
    // 检查是否有新创建的新闻（使用sessionStorage确保只显示一次）
    const showSuccessMessage = sessionStorage.getItem('showNewsCreateSuccess');
    if (showSuccessMessage === 'true') {
      // 清除sessionStorage中的标记
      sessionStorage.removeItem('showNewsCreateSuccess');
      
      // 移除成功提示弹窗，改善用户体验
      // if (this.$message) {
      //   this.$message.success('新闻创建成功！');
      // } else {
      //   alert('新闻创建成功！');
      // }
    }
    
    // 清除URL中的查询参数（如果存在）
    if (this.$route.query.newNewsCreated === 'true') {
      this.$router.replace({
        path: '/news'
      });
    }
    
    // 页面加载时自动调用接口获取新闻列表
    this.loadNewsList();
  },
  methods: {

    // 加载新闻列表
    async loadNewsList() {
      this.loading = true;
      
      try {
        logger.log('📋 [News] 开始获取新闻列表...');
        
        const response = await newsApi.getNewsList();
        
        logger.log('📋 [News] API响应:', response);
        
        // 处理API返回的数据
        if (response && Array.isArray(response.data)) {
          this.newsList = response.data.map(item => ({
            ...item,
            date: this.formatDate(item.releaseTime || item.createdAt || item.date),
            id: item.id || item.newsId || new Date().getTime() + Math.random()
          }));
          this.total = response.total || response.data.length;
        } else if (Array.isArray(response)) {
          // 如果直接返回数组
          this.newsList = response.map(item => ({
            ...item,
            date: this.formatDate(item.releaseTime || item.createdAt || item.date),
            id: item.id || item.newsId || new Date().getTime() + Math.random()
          }));
          this.total = response.length;
        } else {
          logger.log('📋 [News] 未知的响应格式:', response);
          this.loadDefaultNews();
        }
        
        logger.log('📋 [News] 新闻列表加载成功，共', this.total, '条');
        
      } catch (error) {
        logger.error('📋 [News] API调用失败:', error);
        
        // 显示错误消息
        const errorMessage = error.response?.data?.message || error.message || '获取新闻列表失败';
        if (this.$message) {
          this.$message.error(errorMessage);
        } else {
          console.error('获取新闻列表失败:', errorMessage);
        }
        
        // API调用失败时使用默认数据
        this.loadDefaultNews();
      } finally {
        this.loading = false;
      }
    },
    
    // 刷新新闻列表
    async refreshNews() {
      logger.log('🔄 [News] 手动刷新新闻列表');
      await this.loadNewsList();
    },
    
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      const day = String(date.getDate()).padStart(2, '0');
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      return `${day} ${year}-${month}`;
    },
    
    // 加载默认新闻数据（API不可用时的备用方案）
    loadDefaultNews() {
      this.newsList = [];
      this.total = 0;
    },
    
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
        this.loadNewsList();
      }
    },
    
    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++;
        this.loadNewsList();
      }
    },
    
    goToPage(page) {
      this.currentPage = page;
      this.loadNewsList();
    },
    
    createNews() {
      this.$router.push('/news/create');
    },
    
    async deleteNews(newsItem) {
      if (!confirm(`确定要删除新闻"${newsItem.title}"吗？此操作不可恢复。`)) {
        return;
      }
      
      try {
        logger.log('🗑️ [News] 开始删除新闻，ID:', newsItem.id);
        
        // 调用删除API
        await newsApi.deleteNews(newsItem.id);
        
        logger.log('🗑️ [News] 新闻删除成功');
        
        // 移除成功提示弹窗，改善用户体验
        // if (this.$message) {
        //   this.$message.success('新闻删除成功！');
        // } else {
        //   alert('新闻删除成功！');
        // }
        
        // 重新加载新闻列表
        await this.loadNewsList();
        
      } catch (error) {
        logger.error('🗑️ [News] 删除新闻失败:', error);
        
        // 显示错误消息
        const errorMessage = error.response?.data?.message || error.message || '删除新闻失败，请重试';
        if (this.$message) {
          this.$message.error(errorMessage);
        } else {
          alert(errorMessage);
        }
      }
    }
  }
};
</script>

<style scoped>
.news-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Helvetica Neue', Arial, sans-serif;
}

.news-header {
  text-align: center;
  margin-bottom: 40px;
  padding-bottom: 20px;
  border-bottom: 2px solid #eee;
}

.news-title {
  font-size: 28px;
  color: #333;
  margin-bottom: 10px;
}

.news-desc {
  font-size: 16px;
  color: #666;
  max-width: 800px;
  margin: 0 auto;
}

.news-container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  padding: 20px;
}

.news-actions {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
  gap: 10px;
}

.btn {
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  border: none;
  transition: background-color 0.3s;
}

.btn-refresh {
  background-color: #2196F3;
  color: white;
}

.btn-refresh:hover {
  background-color: #1976D2;
}

.btn-refresh:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.btn-create {
  background-color: #4CAF50;
  color: white;
}

.btn-create:hover {
  background-color: #43A047;
}

.btn-delete {
  background-color: #f44336;
  color: white;
}

.btn-delete:hover {
  background-color: #e53935;
}

.btn-delete:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.loading-container {
  text-align: center;
  padding: 40px 20px;
}

.loading-spinner {
  display: inline-block;
  width: 40px;
  height: 40px;
  border: 3px solid rgba(0, 0, 0, 0.1);
  border-radius: 50%;
  border-top-color: #4CAF50;
  animation: spin 1s ease-in-out infinite;
  margin-bottom: 10px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.news-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.news-item {
  padding: 15px 0;
  border-bottom: 1px solid #eee;
}

.news-item-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.news-info {
  flex-grow: 1;
}

.news-date {
  font-size: 14px;
  color: #999;
  margin-right: 15px;
  display: block;
}

.news-item-title {
  font-size: 18px;
  color: #333;
  margin: 10px 0;
  display: inline-block;
  max-width: 100%;
}

.view-detail {
  color: #3e8ef7;
  text-decoration: none;
  font-size: 14px;
}

.view-detail::after {
  content: "__";
  display: inline-block;
  margin-left: 5px;
}

.news-item-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.btn-delete-item {
  background-color: #f44336;
  color: white;
  padding: 6px 12px;
  font-size: 12px;
  border-radius: 4px;
}

.btn-delete-item:hover {
  background-color: #e53935;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 30px;
  font-size: 14px;
}

.pagination span {
  color: #666;
}

.page-btn {
  color: #3e8ef7;
  text-decoration: none;
  margin: 0 10px;
}

.page-number {
  display: inline-block;
  width: 30px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  margin: 0 5px;
  cursor: pointer;
  border-radius: 4px;
}

.page-number.active {
  background-color: #3e8ef7;
  color: white;
}

.page-btn.disabled {
  color: #ccc;
  cursor: not-allowed;
}

@media (max-width: 768px) {
  .news-date {
    display: block;
    margin-bottom: 5px;
  }
  
  .news-item-title {
    max-width: 100%;
    font-size: 16px;
  }
  
  .view-detail {
    font-size: 12px;
  }
}
</style> 